<?php

namespace app\api\model;
use think\Db;
use GatewayClient\Gateway;

class ChatLists extends Common
{
    public function msgtype($content, $channel)
    {
        return _msgtype($content, $channel);
    }

    // 更新会话列表
    static public function updateLists($from_user, $to_user, $single = 0, $channel = 0, $content = '', $fate = 0)
    {
        $ChatListsModel = new ChatLists;
        
        $current_time = time();
        
        if ($channel !== 0) {
            switch ($channel) {
                case 1:
                    $content = '[图片]';
                    break;
                case 2:
                    $content = '[语音]';
                    break;
                case 3:
                    $content = '[视频]';
                    break;
                case 6:
                    $content = '[位置]';
                    break;
                case 8:
                    $content = '[礼物]';
                    break;
                case 9:
                    $content = '[语音通话]';
                    break;
                case 10:
                    $content = '[视频通话]';
                    break;
            }
        }
        
        $user_id = min($from_user, $to_user);
        $another_id = max($from_user, $to_user);
        
        $lists = $ChatListsModel->where(['user_id' => $user_id, 'another_id' => $another_id])->find();

        $from = input('from', 1);
        
        if ($user_id == $from_user) { // 发送者ID比对方小
            $field_channel = 'another_channel';
            $field_unread = 'another_unread';
            $field_untip = 'another_untip';
            $field_content = 'another_content';
            $field_delete = 'another_delete';
            $field_time = 'another_time';
            $field_first = 'user_first';

            $field_content_both = 'user_content';
            $field_channel_both = 'user_channel';
            $field_time_both = 'user_time';
            $field_delete_both = 'user_delete';
            $field_first_both = 'another_first';
        } else {
            $field_channel = 'user_channel';
            $field_unread = 'user_unread';
            $field_untip = 'user_untip';
            $field_content = 'user_content';
            $field_delete = 'user_delete';
            $field_time = 'user_time';
            $field_first = 'another_first';

            $field_content_both = 'another_content';
            $field_channel_both = 'another_channel';
            $field_time_both = 'another_time';
            $field_delete_both = 'another_delete';
            $field_first_both = 'user_first';
        }
        
        if ($lists) {
            $update = [
                'id' => $lists['id'],
                $field_content => $content,
                $field_channel => $channel,
                $field_unread => $lists[$field_unread] + 1,
                $field_untip => $lists[$field_untip] + 1,
                $field_delete => 0,
                $field_time => $current_time,
                'user_first' => 0,
                'another_first' => 0,
            ];
            
            // 非单边消息，发送方列表也更新
            if (!$single) {
                $update[$field_content_both] = $content;
                $update[$field_channel_both] = $channel;
                $update[$field_time_both] = $current_time;
            } else if ($single == 2) {
                // 仅发出方可见
                $update = ['id'=>$lists['id']];
                unset($update[$field_delete]);
                unset($update[$field_delete_both]);
                $update[$field_content_both] = $content;
                $update[$field_channel_both] = $channel;
                $update[$field_time_both] = $current_time;
            }
            
            $ChatListsModel->update($update);
        } else {
            $create = [
                'user_id' => $user_id,
                'another_id' => $another_id,
                $field_content => $content,
                $field_channel => $channel,
                $field_unread => 1,
                $field_untip => 1,
                $field_time => $current_time,
                $field_first => $fate,
            ];
            
            // 非单边消息，发送方列表也更新
            if (!$single) {
                $create[$field_content_both] = $content;
                $create[$field_channel_both] = $channel;
                $create[$field_time_both] = $current_time;
            } else if ($single == 2) {
                // 仅发出方可见
                $create = [
                    'user_id' => $user_id,
                    'another_id' => $another_id,
                    $field_content => $content,
                    $field_channel => $channel,
                    $field_unread => 0,
                    $field_untip => 0,
                    $field_time => $current_time,
                    $field_first=>$fate==2?0:1,
                    $field_delete=>1
                ];
                $create[$field_content_both] = $content;
                $create[$field_channel_both] = $channel;
                $create[$field_time_both] = $current_time;
            }

            $create['from'] = $from;
            
            $ChatListsModel->create($create);
        }
    }
    
    public function changeLists($from_user, $to_user, $field = 'unread', $status=0)
    {
        $ChatListsModel = new ChatLists;
        
        $user_id = min($from_user, $to_user);
        $another_id = max($from_user, $to_user);
        
        $lists = $ChatListsModel->where(['user_id' => $user_id, 'another_id' => $another_id])->find();
        
        if ($user_id == $from_user) {
            $field_change = 'user_';
        } else {
            $field_change = 'another_';
        }
        
        if ($lists) {
            if (in_array($field, ['delete_one', 'delete_all'])) {
                if ($field == 'delete_all') {
                    $update = [
                        'id' => $lists['id'],
                        $field_change . 'content' => '',
                        $field_change . 'unread' => 0,
                        $field_change . 'delete' => 1,
                    ];
                } else if ($field == 'delete_one') {
                    $Privatechat = new Privatechat;
                    $newest = $Privatechat->where([
                        'type' => ['neq', -1],
                        'single' => 0,
                        'userid' => $from_user,
                        'touserid' => $to_user,
                        'status' => ['in', [0,2]]
                    ])->whereOr(function ($query) use ($to_user, $from_user) {
                        $query->where([
                            'type' => ['neq', -1],
                            'single' => 0,
                            'userid' => $to_user,
                            'touserid' => $from_user,
                            'status' => ['in', [0,1]]
                        ]);
                    })->order('id desc')->find();


                    if($newest){
                        $newest['content'] = $this->msgtype($newest['content'], $newest['type']);
                    }
                    
                    $update = [
                        'id' => $lists['id'],
                        $field_change . 'content' => $newest ? $newest['content'] : '[消息已删除]',
                        $field_change . 'unread' => 0,
                    ];
                }
            } else if ($field == 'recall') {
                if ($user_id == $from_user) {
                    $field_change = 'another_';
                    $field_change_another = 'user_';
                } else {
                    $field_change = 'user_';
                    $field_change_another = 'another_';
                }
                
                $Privatechat = new Privatechat;
                $newest = $Privatechat->where([
                    'type' => ['neq', -1],
                    'single' => 0,
                    'userid' => $from_user,
                    'touserid' => $to_user,
                    'status' => ['in', [0,2]]
                ])->whereOr(function ($query) use ($to_user, $from_user) {
                    $query->where([
                        'type' => ['neq', -1],
                        'single' => 0,
                        'userid' => $to_user,
                        'touserid' => $from_user,
                        'status' => ['in', [0,1]]
                    ]);
                })->order('id desc')->find();
                
                $update = [
                    'id' => $lists['id'],
                    $field_change . 'content' => $newest ? $newest['content'] : '[消息已撤回]',
                    $field_change_another . 'content' => '[消息已撤回]',
                    $field_change . 'unread' => $lists[$field_change . 'unread'] ? $lists[$field_change . 'unread'] - 1 : 0,
                ];
            } else {
                $update = [
                    'id' => $lists['id'],
                    $field_change . $field => $status,
                ];
                
                // 删除列表也做已读
                if ($field == 'delete') {
                    $update[$field_change . 'unread'] = 0;
                }
            }
            
            $ChatListsModel->update($update);
        }
    }
    
    public function synchLists($userid, $data='')
    {
        $ChatListsModel = new ChatLists;
        $ChatListsRecordsModel = new ChatListsRecords;
        
        if ($data) {
            // 有会话记录的用户
            $ids = $ChatListsModel->where(['user_id|another_id' => $userid])->column('id, user_id, another_id');
            
            $uids = [];
            $lists_ids = [];
            foreach ($ids as $key => $item) {
                $uids[] = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];
                $another_id = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];
                $lists_ids[$another_id] = $key;
            }
            
            $create_user = [];
            $create_another = [];
            $update_user = [];
            $update_another = [];
            foreach ($data as $key => $item) {
                $touserid = $item['touserid'] != $userid ? $item['touserid'] : $item['userid'];
                
                $user_id = min($touserid, $userid);
                $another_id = max($touserid, $userid);
                
                if ($user_id == $userid) { // ID小
                    $field_channel = 'user_channel';
                    $field_unread = 'user_unread';
                    $field_content = 'user_content';
                    $field_delete = 'user_delete';
                    $field_time = 'user_time';
                    $field_top = 'user_top';
                } else {
                    $field_channel = 'another_channel';
                    $field_unread = 'another_unread';
                    $field_content = 'another_content';
                    $field_delete = 'another_delete';
                    $field_time = 'another_time';
                    $field_top = 'another_top';
                }
                
                if (in_array($touserid, $uids)) {
                    if ($user_id == $userid) {
                        $update_user[] = [
                            'id' => $lists_ids[$touserid],
                            $field_content => $item['content'],
                            $field_channel => $item['type'],
                            $field_unread => $item['count'],
                            $field_delete => 0,
                            $field_time => $item['sort_field'],
                            $field_top => $item['top'],
                        ];
                    } else {
                        $update_another[] = [
                            'id' => $lists_ids[$touserid],
                            $field_content => $item['content'],
                            $field_channel => $item['type'],
                            $field_unread => $item['count'],
                            $field_delete => 0,
                            $field_time => $item['sort_field'],
                            $field_top => $item['top'],
                        ];
                    }
                } else {
                    if ($user_id == $userid) {
                        $create_user[] = [
                            'user_id' => $user_id,
                            'another_id' => $another_id,
                            $field_content => $item['content'],
                            $field_channel => $item['type'],
                            $field_unread => $item['count'],
                            $field_time => $item['sort_field'],
                            $field_top => $item['top'],
                        ];
                    } else {
                        $create_another[] = [
                            'user_id' => $user_id,
                            'another_id' => $another_id,
                            $field_content => $item['content'],
                            $field_channel => $item['type'],
                            $field_unread => $item['count'],
                            $field_time => $item['sort_field'],
                            $field_top => $item['top'],
                        ];
                    }
                    
                }
            }
            
            if ($create_user) {
                $ChatListsModel->saveAll($create_user);
            }
            if ($create_another) {
                $ChatListsModel->saveAll($create_another);
            }
    
            if ($update_user) {
                $ChatListsModel->saveAll($update_user);
            }
    
            if ($update_another) {
                $ChatListsModel->saveAll($update_another);
            }
        }
        
        $ChatListsRecordsModel->create(['user_id' => $userid]);
    }


    public static function pushNewMsg($data)
    {
        $userid = $data['userid'];
        $touserid = $data['touserid'];
        $result = $data;

        if(!isset($result['type'])){ $result['type'] = 0; }
        if(!isset($result['status'])){ $result['status'] = "0"; }
        if(!isset($result['state'])){ $result['state'] = "0"; }
        if(!isset($result['second'])){ $result['second'] = "0"; }
        if(!isset($result['is_burn'])){ $result['is_burn'] = "0"; }
        if(!isset($result['k'])){ $result['k'] = "0"; }
        if(!isset($result['money'])){ $result['money'] = '0.00'; }
        if(!isset($result['score'])){ $result['score'] = '0.00'; }
        if(!isset($result['location'])){ $result['location'] = "0"; }
        if(!isset($result['isRead'])){ $result['isRead'] = "0"; }
        if(!isset($result['isCount'])){ $result['isCount'] = "0"; }
        if(!isset($result['sound_tip'])){ $result['sound_tip'] = "0"; }
        if(!isset($result['sms_tip'])){ $result['sms_tip'] = "0"; }
        if(!isset($result['is_public'])){ $result['is_public'] = "0"; }
        if(!isset($result['is_fate'])){ $result['is_fate'] = "0"; }
        if(!isset($result['order_id'])){ $result['order_id'] = "0"; }
        if(!isset($result['front_id']) || $result['front_id']==0){ $result['front_id'] = ""; }
        if(!isset($result['addtime'])){ $result['addtime'] = date('Y-m-d H:i:s'); }

        $data = ['new' => [], 'recall' => [], 'users' => ['userid' => $touserid, 'touserid' => $userid, 'intimate' => 0]];
    
        $users = User::where(['id' => ['in', [$userid, $touserid]]])->cache(86400)->column('id, name, head_100 head_portrait, sex, reg, authcode');


        if ($result) {
            $result['self'] = $userid == $result['userid'] ? 1 : 0;

            $result['name'] = $users[$result['userid']]['name'];
            $result['head_portrait'] = $users[$result['userid']]['head_portrait'];

            $datas = json_decode($result['data'], true);

            if (isset($datas['image'])) {
                $datas['image'] = changeUrl($datas['image']);
            }

            if (in_array($result['type'], [9, 10])) {
                if (isset($datas['status']) && $datas['status']) {
                    if (isset($datas['start']) && isset($datas['end'])) {
                        $chat_time = $datas['end'] - $datas['start'];
                        $result['chat_time'] = changeTimeLen($chat_time);
                    } else {
                        if ($datas['second']) {
                            $result['content'] .= changeTimeLen($datas['second'] * 60);
                        } else {
                            $result['content'] .= '00:59';
                        }
                    }
                    if($result['type'] == 9){
                        UserActiveval::inc($userid, 'chatforaudio');
                    }else{
                        UserActiveval::inc($userid, 'chatforvideo');
                    }
                } else {
                    $result['content'] .= ' 未接通';
                }
            }else{
                UserActiveval::inc($userid, 'chatformsg');
            }

            $result['data'] = $datas;

            $data['new'][] = $result;

            $couple_a = $userid < $touserid ? $userid . ',' . $touserid : $touserid . ',' . $userid;
            $intimate = UserIntimate::where(['couple_a' => $couple_a])->value('intimate');

            $data['users']['intimate'] = $intimate ? $intimate/10: 0;
        }

        $contain = $data;
        foreach ($contain['new'] as $k => $v) {
            $v['self'] = $v['self'] ? 0 : 1;
            $contain['new'][$k] = $v;
        }

        if (!empty($data['new']) || !empty($data['recall'])) {
            if (isset($result[0]) && $result[0]['single']) {
                $data = [];
            }
            $message1 = json_encode(['code' => 200, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $contain, 'user_id'=>$touserid]);
            $message2 = json_encode(['code' => 200, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $data, 'user_id'=>$userid]);
        } else {
            $message1 = $message2 = json_encode(['code' => 400, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => []]);
        }

        if ($users[$touserid]['reg'] == 2) {
            $touserid = Db::name('user')->where(['id'=>$users[$touserid]['authcode']])->value('id');
        }
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message1);
        if($result['single']==0){
            if ($users[$userid]['reg'] == 2) {
                $userid = Db::name('user')->where(['id'=>$users[$userid]['authcode']])->value('id');
            }
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $message2);
        }
    }
}

